/**
 * Copyright (c) 2019 Coder League
 * All rights reserved.
 *
 * File：EnumConverterConfigurer.java
 * History:
 *         2019年6月10日: Initially created, CJH.
 */
package club.coderleague.ilsp.common.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import club.coderleague.ilsp.common.domain.enums.BaseEnum;

/**
 * 枚举转换工厂配置
 * 
 * @author CJH
 */
public class EnumConverterConfigurer implements ConverterFactory<String, BaseEnum> {
	 
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
    	return new StringToEnum<T>(targetType);
    }
 
    /**
     * 字符串转换为枚举
     * 
     * @author CJH
     */
    class StringToEnum<T extends BaseEnum> implements Converter<String, T> {
    	
    	/**
    	 * 枚举类型
    	 */
        private final Class<T> enumType;
 
        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }
 
        @Override
        public T convert(String source) {
        	if (source.length() <= 0) {
        		return null;
        	}
        	T[] enums = enumType.getEnumConstants();
    		for (T e : enums) {
    			if (source.equals(e.getPrimaryKey())) {
    				return e;
    			}
    		}
    		return null;
        }
    }
}